<?php

namespace app\index\controller\tan;

use think\Controller;
use think\Request;
use think\Session;
use think\Db;
use app\index\model\tan\Store as S;
use app\index\controller\Sms\AliYunSms;
/**
 * 门店管理
 */
class Store extends Controller
{
    use UploadFileTrait;


    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(Request $request, S $s)
    {  
        $postData = $request->post();
        $searchName = isset($postData['name']) ? $postData['name'] : '';
        $page       = isset($postData['page']) ? $postData['page'] : 1;
        if(Session::get('user.is_shop') > 0){
            $where['s.user_id'] = Session::get("user.id");
        }elseif(Session::get('user.is_business') > 0){
            $where['s.business_id'] = Session::get("user.id");
        }
        $where['s.state'] = 0;
        $stores = $s->alias("s")
                ->join("users u ","u.id=s.user_id")  
                ->where($where)
                ->where('s.store_name','like', '%'.$searchName.'%')
                ->field("s.*,u.phone, u.card_balance,u.is_identity") 
                ->order("s.id desc")
                ->limit(($page-1)*20,$page*20-1)//->fetchSql()
                ->paginate();
        return ['code' => 666, 'msg' => '商店列表', 'data' => $stores];
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }
    /**
     * 店铺信息（店铺认证）
     * @param Request $R
     * @param S $s
     */
    public function save2(Request $R){
        $data=$R->post();
        $r=[
            "name|名称"=>"require",
            "storename|店铺名称"=>"require",
            "code|短信"=>"require|number", 
 //           "itype|身份类型"=>"require",
//          "identity_id|身份证"=>"require|max:18|^[0-9]{17}[0-9A-Za-z]{1}$",
            "identity_id|身份证号"=>"require|max:18",
            "identity_holder|手持身份证照"=>"require",
            "identityurl|身份证正面照"=>"require",
            "identity_url|身份证反面照"=>"require",
  //          "license|营业执照"=>"require",
        ];
        Ret::IfNoTrue($this->validate($R->post(), $r), 10200);
        if($data['code'] != Session::get("sms_code")){
            Ret::err(10300, "短信验证码错误");
        }
        // $r1=[
        //     "main|主运营"=>"require",
        //     "license|营业执照"=>"require",
        // ];
        // Ret::IfNoTrue($this->validate($R->post(), $r1), 10201);
        $d= Db::table("store")->where([
            "store_name"=>$data['storename'],
            "user_id"=> Session::get("user.id"),
        ])->find();
        Ret::IfEmpty($d, 12222,"门店不存在");
        Db::table("users")->where([
           // "higherups"=>Session::get("user.id"),
            "id"=>Session::get("user.id"),
        ])->update([
            "name"=>$data['name'],
            "itype"=>0,
            'is_identity' => 2,
        ]);
        Db::table("identity")->insert([
            "user_id"=>Session::get("sms_u_id"),
            "createtime"=>date("Y-m-d H:i:s"),
            "name"=>$data['name'],
            "identity_id"=>$data['identity_id'],
            "identityurl"=> $data['identityurl'],
            "identity_url"=>$data['identity_url'],
            "identity_holder"=>$data['identity_holder'],

        ]);
       Db::table("store")->where([
           "user_id"=>Session::get("user.id")
       ])->update([
           //"main"=>$data['main'],
           //"license"=>$data['license'],
           "itype"=>0,
           "is_identity"=>1,
       ]);
       Ret::ok();
        
    }
    /**
     * 发送短信
     * @param AliYunSms $AliYunSms
     * @param string $storename 门店名称
     */
    public function sms(AliYunSms $AliYunSms, Request $R){
        Ret::IfNoTrue($this->validate($R->post(), ["storename|门店名称"=>"require"]) ,12133);
        $d= Db::table("store")->alias("s")->join("users u","u.id=s.user_id")->where([
            "s.store_name"=>$R->post("storename"),
            ])->where(function($query){
                $query->whereOr([
                   //"s.business_id"=> Session::get("user.id"),
                    "s.user_id"=> Session::get("user.id"), 
                ]);
            })->field("s.*,u.phone") ->find();
        Ret::IfEmpty($d, 12222,"非本人的门店");
        if(! $d['phone']){
            Ret::err(10233,"无电话");
        }
        $code= rand(1000, 9999);
        Session::set("sms_code",$code);
        Session::set("sms_u_id",$d['user_id']);
        Session::set("sms_id",$d['id']);

        return $AliYunSms->code_type($code) ->setRecNum($d['phone']);
    }
    /**
     * 创建门店
     * @param Request $request
     * @param S $s
     */
    public function save(Request $request,S $s)
    {
        $rule=[
            "store_name|门店名称"=>"require|chsDash",
            "store_description|门店描述"=>"max:255",
            "phone|手机号码"=>"require|number",
            "date|时间"=>"require|date",
            "close_date|时间"=>"require|date",
            "address|地址"=>"require",
        ];
       $ret= $this->validate($request->post() ,$rule );
       Ret::IfNoTrue($ret, 10120);
       $u=Db::table("users")->where([
           "phone"=>$request->post('phone'),
           "state"=>0
       ])->find();
       if(empty($u)){
           $id= Db::table("users")->insertGetId([
                    "superior_id" => Session::get("user.id"),
                     "system_id"=>1,
                     "is_business"=>0,
                     "phone"=>$request->post("phone"),
                     "password" => "888888",
                     "name"   =>$request->post('store_name'),
                     "shop" => 1,
                     "is_staff" => 1,
                     "is_customer"=>0,
                 ]);
       }else{
           if($u['is_business'] !== 0){
               Ret::err(10300,"已经是商家，不可以改为门店");
           }
           if($u['shop'] !== 0){
               Ret::err(10301,"已经是门店");
           }
           $id=$u['id'];
       }
      
        $d=$request->post();
        unset($d['phone']);
        ReturnData::IfTrue($ret, 11101);
        $data = Eliminate::E($d, $rule);
        $data['business_id']=Session::get("user.id");
        $data['store_logurl']=$request->post("store_logurl");
        $data['createtime']=date("Y-m-d H:i:s");
        $data['user_id']=$id;
        $data['state']=0;
        $s->insert($data);
        $store_id=Db::table('store')->getLastInsID();//获取刚插入数据的id
        
            //2018-06-28 刘家腾  门店店长数据同步到员工表
            $staffdate['business_id']=Session::get("user.id");
            $staffdate['store_id']=$store_id;//门店
            $staffdate['user_id']=$id;
            $staffdate['name']=$request->post('store_name');
            $staffdate['phone']=$request->post("phone");
            $staffdate['position_id']=1;//职位
            $staffdate['department_id']=1;//部门
            $staffdate['supervisor_id']=Session::get("user.id");
            $staffdate['is_hire']=1;//是否外聘
            $staffdate['createtime']=date('Y-m-d H:i:s');
            Db::table('staff') ->data($staffdate) ->insert();
        ReturnData::ok();
       
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     *刘家腾
     *2018-5-18
     *获取门店详情
     * Gets the storeinfo.
     */
    public function get_storeinfo(Request $request,S $s)
    {
        $rule=[
            "store_id|门店ID"=>"require",
        ];
        $post= $this->validate($request->post() ,$rule );
        $post_list=$request->post();
        $map['s.user_id']=$post_list['store_id'];
        $map['s.state']=0;
        $data['code']=666;
        $data['msg']="获取店铺详情成功！";
        $data['data']='';
        $data['data']=Db::table('store')
                                    ->alias('s')
                                    ->join('users u', 's.user_id = u.id', 'LEFT')
                                    ->where($map)
                                    ->field('s.*, u.phone')
                                    ->select();
        if(empty($data['data'])){
            $data['msg']="没有查到你输入的店铺信息！";
        }
        return $data;
    }
    /**
     * 
     * 保存更新的资源
     *
     * @return \think\Response
     * @param Request $request
     * @param S $s
     * @param type $id  门店id
     */
    public function update(Request $request,S $s, $id)
    {
        $rule=[
            "store_name|门店名称"=>"require|chsDash",
            "store_description|门店描述"=>"max:255",
            "date|时间"=>"require|date",
            "close_date|时间"=>"require|date",
            "address|地址"=>"require",
        ];

        $ret= $this->validate($request->post() ,$rule );
        Ret::IfNoTrue($ret, 11105);

        $data = Eliminate::E($request->post(), $rule);

        $data['store_logurl'] =$request->post("store_logurl");
        unset($data['phone']);
        $d=$s->where([
            "user_id"=>$id,
            'business_id'=>Session::get("user.id"),
            ])
        ->update($data);

        Ret::ok();
    }

    /**
     * 删除指定资源
     * @param  int  $id
     * @return \think\Response
     */
    public function delete(S $s,$id)
    {
        //
        ReturnData::exit_(
                $s->where([
                        'business_id'=>Session::get("user.id"),
                        "state"=>0,
                        "user_id"=>$id
                    ])->update(["state"=>1,])
                ,
                11103
                ,
                [],
                "删除失败，无权操作或已经被删除"
            );
    }
}
